package serveur;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Serveur version HTTP Sequentiel, version simple. Ne gere qu'un seul client a
 * la fois et seulement les requetes de type GET
 * 
 * @author Erik & Lucas
 * 
 */
public class ServeurHTTPSequentiel {

	private static ServerSocket serveurSocket;

	public static void main(String[] args) {
		try {
			serveurSocket = new ServerSocket(2009);
			System.out.println("Serveur lance sur le port: 2009, en attente de connexion d'un client");
			while (true) {
				Socket socket = serveurSocket.accept();

				System.out.println("Connexion TCP etablie");

				BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

				PrintWriter out;

				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

				String message = "";
				out.println("Connexion TCP etablie");

				boolean continuer = true;
				// Permet de gérer l'envoie et la récéption du plusieurs
				// messages
				while (continuer == true) {
					message = in.readLine();
					System.out.println(message);
					String text = "";
					if (getTypeRequete(message).equals("GET")) {
						if (verifierRequeteGet(message)) {
							String[] requete = message.split(" ");

							// Si le fichier existe on continue
							File fichier = new File(requete[1]);
							if (fichier.exists()) {
								// On met dans une chaine le contenu du fichier
								text = _GET(message, out);
								text = text + "\n <CR> <LF>";
							} else {
								text = "HTTP/1.1 404 Not Found \n <CR> <LF>";
							}
						} else {
							text = "HTTP/1.1 400 Bad Request \n <CR> <LF>";
						}
					} else if (message.equalsIgnoreCase("FIN")) {
						continuer = false;
					} else {
						text = "HTTP/1.1 400 Bad Request \n <CR> <LF>";

					}
					out.println(text);
				}
				System.out.println("Fermeture de la connexion du client");
				in.close();
				out.close();
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static String _GET(String message, PrintWriter out) throws IOException {
		String text = "";
		String[] requete = message.split(" ");
		File fichier = new File(requete[1]);
		String nomFichier = requete[1];
		double taille = fichier.length();
		if (fichier.exists()) {
			BufferedReader br = null;
			String ligne = "";
			text = "HTTP/1.1 200 OK \n";
			text = text + "Content-length: " + taille + "\n";
			br = new BufferedReader(new FileReader(nomFichier));
			while ((ligne = br.readLine()) != null) {
				text = text + ligne + "\n";
			}
		}
		return text;
	}

	private static String getTypeRequete(String message) {
		return message.split(" ")[0];
	}

	private static boolean verifierRequeteGet(String message) {
		boolean verification = false;
		String[] requete = message.split(" ");
		if (requete.length == 5) {
			if (requete[0].equals("GET") && (requete[2].equals("HTTP/1.1") || requete[2].equals("HTTP/1.0")) && requete[3].equals("<CR>") && requete[4].equals("<LF>")) {
				verification = true;
			}
		}
		return verification;
	}
}
